<!-- 采购合同编辑 -->
<template>
  <div class="registerDetail">
    <van-nav-bar
      :title="$route.meta.title"
      left-text="返回"
      left-arrow
      :fixed="true"
      :placeholder="true"
      @click-left="$router.go(-1)"
    />
    <!-- 表单 -->
    <div class="formData">
      <van-form ref="form">
        <van-field
          readonly
          v-model="formData.billNumber"
          name="采购编号"
          label="采购编号"
          input-align="right"
          placeholder="请输入"
        />

        <van-field
          v-model="formData.bizDate"
          name="付款日期"
          label="付款日期"
          input-align="right"
          placeholder="请选择"
          right-icon="arrow"
          @click="handleSelectTime('bizDate')"
          readonly
        />
        <van-field
          v-model="formData.payType"
          readonly
          name="款项性质"
          label="款项性质"
          input-align="right"
          placeholder="请选择"
          right-icon="arrow"
          @click="handleSelect('payTypeValue', 'payType')"
        />
        <van-field
          v-model="formData.signCompany"
          readonly
          name="签约公司"
          label="签约公司"
          input-align="right"
          placeholder="请选择"
          right-icon="arrow"
          @click="handleSelect('signCompanyId', 'signCompany')"
        />
        <van-field
          v-model="formData.paymentType"
          readonly
          name="付款方式"
          label="付款方式"
          input-align="right"
          placeholder="请选择"
          right-icon="arrow"
          @click="handleSelect('paymentTypeValue', 'paymentType')"
          :rules="[{ required: true }]"
        />
        <van-field
          v-model="formData.bankAccount"
          readonly
          name="付款账号"
          label="付款账号"
          input-align="right"
          placeholder="请选择"
          right-icon="arrow"
          @click="handleSelect('bankAccountId', 'bankAccount')"
          :rules="[{ required: true }]"
        />

        <van-field
          required
          v-model="formData.remark"
          name="备注"
          label="备注"
          type="textarea"
          input-align="left"
          placeholder=""
        />
        <!-- <van-field
          v-model="formData.customerName"
          name="客户名称"
          label="客户名称"
          input-align="right"
          placeholder="请输入"
        /> -->
        <div class="car_title">二手车供应商</div>
        <van-field
          required
          v-model="formData.shSupplier"
          name="二手车供应商"
          label="二手车供应商"
          input-align="right"
          placeholder="请输入"
        />
        <van-field
          v-model="formData.shSupplierBank"
          name="二手车供应商银行"
          label="二手车供应商银行"
          input-align="right"
          placeholder="请选择"
          label-width="120px"
          :rules="[{ required: true }]"
        />
        <van-field
          v-model="formData.shSUpplierAccount"
          name="二手车供应商账号"
          label="二手车供应商账号"
          input-align="right"
          placeholder="请输入"
          label-width="120px"
          :rules="[{ required: true }]"
        />
        <div class="car_title">付款车辆信息</div>

        <van-field
          readonly
          v-model="billNumber"
          name="采购合同号"
          label="采购合同号"
          input-align="right"
          placeholder="请输入"
        />
        <van-field
          readonly
          v-model="formData.vinCode"
          name="车架号"
          label="车架号"
          input-align="right"
          placeholder="请输入"
        />

        <van-field
          v-model="formData.actPayAmount"
          name="金额"
          label="金额"
          input-align="right"
          type="number"
          placeholder="请输入"
          :rules="[{ required: true }]"
          @blur="changePrice"
        />
        <div v-if="formData.payTypeValue == 2">
          <van-field
            v-model="formData.trdDisbursements"
            name="第三方采购垫付额"
            label="第三方采购垫付额"
            input-align="right"
            type="number"
            placeholder="请输入"
            label-width="120px"
            :rules="[{ required: true }]"
            @blur="changeThPrice"
          />
          <van-field
            v-model="formData.trdReceived"
            name="第三方实收额"
            label="第三方实收额"
            type="number"
            input-align="right"
            placeholder="请输入"
            :rules="[{ required: true }]"
          />
        </div>

        <!-- 下拉选择弹窗 -->
        <van-popup v-model="showSelectPicker" position="bottom">
          <van-field
            name="模糊查询"
            v-if="likeWhoField == 'signCompanyId'"
            input-align="left"
            v-model="likeWho"
            label="模糊查询"
            placeholder="请输入模糊查询关键词"
          />
          <van-picker
            show-toolbar
            :columns="columns"
            @confirm="handleSelectConfirm"
            @cancel="showSelectPicker = false"
            value-key="name"
          />
        </van-popup>

        <!-- 时间选择弹窗 -->
        <van-popup v-model="showTimerPicker" position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="date"
            @confirm="onTimeConfirm($event)"
            @cancel="showTimerPicker = false"
            :formatter="formatter"
          />
        </van-popup>
        <div class="footerBtn">
          <div class="saveBtn" @click="formOnSubmit(1)">保存</div>
          <div class="submitBtn" @click="formOnSubmit(2)">提交</div>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import {
  Search,
  Empty,
  Field,
  Form,
  Uploader,
  DatetimePicker,
  Tab,
  Tabs,
  ImagePreview,
  Notify,
} from "vant";
import { getCookies } from "@/utils/util.js";
import sellManageApi from "@/api/sellManageApi";
import commonApi from "@/api/commonApi";
export default {
  name: "PaymentOrderEdit",
  components: {
    Search,
    Empty,
    Field,
    Form,
    Uploader,
    DatetimePicker,
    Tab,
    Tabs,
    ImagePreview,
    Notify,
  },
  data() {
    return {
      showTimerPicker: false,
      formData: {
        billId: "", //单据ID
        billNumber: "", //单据编号
        payType: "", //款项性质
        payTypeValue: "", //款项性质
        bandName: "", //所属品牌
        bandId: "", //所属品牌Id
        showOrgName: "", //所属展厅
        showOrgId: "", //所属展厅
        signCompany: "", //签约公司
        signCompanyId: "", //签约公司
        bankAccount: "", //付款账号
        bankAccountId: "", //付款账号
        bizDate: "", //付款日期
        actPayAmount: "", //实际付款金额
        tatalAmount: "", //合计付款金额
        remark: "", //备注
        shSupplier: "", //二手车供应商
        shSupplierBank: "", //二手车供应商银行
        shSUpplierAccount: "", //二手车供应商账号,提交必填
        trdDisbursements: "",
        trdReceived: "",
      },
      orderId: "",
      billNumber: "",

      columns: [],
      showSelectPicker: false,
      detailId: "",
      userId: getCookies("userId"), //用户ID，必填，String
      isflagList: [
        { name: "是", value: 1 },
        { name: "否", value: 0 },
      ],
      currentDate: new Date(),
      showOrgList: [],
      payTypeList: [],
      showCompanyList: [],
      showbankAccountList: [],
      paymentTypeList: [],
      likeWhoField:'',
      likeWho:'',
    };
  },
  watch:{
    likeWho: function (nval, oval) {
      if (nval) {
        let newArr = this.showCompanyList.filter((item) => {
          return item.name.indexOf(nval) > -1;
        });
        console.log(newArr);
        this.columns = newArr;
      } else {
        this.columns = this.showCompanyList;
      }
    },
  },
  mounted() {
    this.getPayType();
    this.getPaymentType();
    this.getCompanyOrgUnit();
    if (this.$route.query) {
      this.detailId = this.$route.query.billId;
      this.getDetail(this.detailId);
      this.orderId = this.$route.query.orderId;
      this.billNumber = this.$route.query.billNumber;
    }
  },
  methods: {
    getDetail(billId) {
      sellManageApi
        .secondHandCarFacade({
          billId,
          method: "getPurchaePaymentById",
        })
        .then((res) => {
          if (res.code == 1) {
            for (const key in res.data) {
              if (res.data[key] == null || res.data[key] == undefined) {
                res.data[key] = "";
              }
            }
            res.data.isNewENergy = res.data.isNewENergy ? 1 : 0;
            res.data.shAccident = res.data.shAccident ? 1 : 0;
            res.data.outsourceResources = res.data.outsourceResources ? 1 : 0;
            this.formData = { ...this.formData, ...res.data };

            console.log(this.formData);
          }
        });
    },
    // 获取款项性质
    getPayType() {
      commonApi
        .getEnums({
          key: "payType",
          userId: this.userId,
        })
        .then((res) => {
          if (res.data) {
            this.payTypeList = res.data;
          }
        });
    },
    // 付款方式

    getPaymentType() {
      commonApi
        .getEnums({
          key: "paymentType",
          userId: this.userId,
        })
        .then((res) => {
          if (res.data) {
            this.paymentTypeList = res.data;
          }
        });
    },
    // 获取签约公司
    getCompanyOrgUnit() {
      sellManageApi
        .secondHandCarFacade({
          method: "getComponyOrgUnit",
        })
        .then((res) => {
          if (res.code == 1) {
            this.showCompanyList = res.data;
          }
        });
    },
    // 获取签约公司
    getPayAccountNumber() {
      sellManageApi
        .secondHandCarFacade({
          method: "getPayAccountNumber",
          signCompanyId: this.formData.signCompanyId,
        })
        .then((res) => {
          if (res.code == 1) {
            this.showbankAccountList = res.data;
            this.columns = this.showbankAccountList;
          }
        });
    },
    // 选择下拉
    handleSelect(field, fieldName) {
      this.showSelectPicker = true;
      if (field == "payTypeValue") {
        console.log(this.payTypeList);
        this.columns = this.payTypeList;
      } else if (field == "showOrgId") {
        this.columns = this.showOrgList;
      } else if (field == "signCompanyId") {
        this.columns = this.showCompanyList;
      } else if (field == "bankAccountId") {
        if (this.formData.signCompanyId) {
          this.getPayAccountNumber();
        } else {
          this.showSelectPicker = false;
          this.$toast.fail("请先选择签约公司");
        }
      } else if (field == "paymentTypeValue") {
        this.columns = this.paymentTypeList;
      }
      this.likeWhoField = field
      this.field = field;
      this.fieldName = fieldName;
    },
    // 选择下拉确认
    handleSelectConfirm(value, index) {
      if (
        this.field == "showOrgId" ||
        this.field == "signCompanyId" ||
        this.field == "bankAccountId"
      ) {
        this.formData[this.field] = value.billId;
        this.formData[this.fieldName] = value.name;
      } else {
        this.formData[this.field] = value.value;
        this.formData[this.fieldName] = value.name;
      }

      this.showSelectPicker = false;
    },

    onConfirm(val, field) {
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let minute = val.getMinutes();
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.formData[field] = `${year}-${month}-${day}`;
      this.showTimerPicker = false;
    },

    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      } else if (type === "hour") {
        return `${value}时`;
      } else if (type === "minute") {
        return `${value}分`;
      } else if (type === "second") {
        return `${value}秒`;
      }
      return value;
    },
    // 时间选择
    handleSelectTime(field) {
      this.timeField = field;
      this.showTimerPicker = true;
    },
    onTimeConfirm(val) {
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let minute = val.getMinutes();
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.formData[this.timeField] = `${year}-${month}-${day} `;
      this.showTimerPicker = false;
    },
    //维修预约
    applyRepair() {
      this.$router.push("/applyRepair");
    },
    // 获取list名称
    getFieldName(list, key, val) {
      if (list && list.length > 0) {
        let obj = list.filter((item) => {
          return item[key] == val;
        });
        if (obj.length > 0) {
          return obj[0].name;
        }
      }
      return null;
    },

    changePrice(val) {
      if (this.formData.payTypeValue == 2) {
        this.formData.trdDisbursements = JSON.parse(
          JSON.stringify(this.formData.actPayAmount)
        );
      }
    },
    changeThPrice() {
      if (this.formData.payTypeValue == 2) {
        this.formData.actPayAmount = JSON.parse(
          JSON.stringify(this.formData.trdDisbursements)
        );
      }
    },
    formOnSubmit(type) {
      console.log(this.formData);
      this.$refs.form
        .validate()
        .then(() => {
          sellManageApi
            .secondHandCarFacade({
              ...this.formData,
              method: "updatePurchaePayment",
              saveOrSubmit: type == 1 ? "save" : "submit",
            })
            .then((res) => {
              console.log(res);
              if (res.code == 1) {
                if (type == 1) {
                  Notify({ type: "success", message: "保存成功" });
                } else {
                  Notify({ type: "success", message: "提交成功" });
                  this.$router.go(-1);
                }
              }
            });
          this.loading = true;
        })
        .catch(() => {
          this.loading = false;
          this.$toast.fail("请完善信息");
        });
    },
  },
};
</script>

<style lang="less" scoped>
body {
  background: #f3f3f3;
}
.flex {
  display: flex;
  align-items: center;
}
.registerDetail {
  overflow: hidden;
  .detail_header {
    justify-content: space-between;
    margin: 0.2rem 0.2rem;
    border-radius: 5px;
    background: #fff;
    padding: 0.3rem;
    .detail_header_lt {
      .carNo {
        font-size: 0.32rem;
        font-weight: bold;
        margin-bottom: 0.2rem;
        .carStatus {
          border: 1px solid #35bc04;
          color: #35bc04;
          border-radius: 5px;
          padding: 0.1rem 0.1rem;
          font-size: 0.24rem;
          text-align: center;
          margin-left: 0.1rem;
        }
      }
      .hank {
        font-size: 0.28rem;
        color: #666;
        .name {
          border-right: 2px solid #ccc;
          padding-right: 0.1rem;
          margin-right: 0.1rem;
        }
      }
    }
    .detail_header_rt {
      justify-content: flex-start;
      .txt {
        font-size: 0.28rem;
        color: #161616;
      }
      .icon-tel {
        color: #fff;
        background: #35bc04;
        font-size: 0.32rem;
        padding: 0.1rem;
        border-radius: 50%;
        margin-right: 0.1rem;
      }
    }
  }
  .formData {
    background: #fff;
    overflow: hidden;
  }
}

.footerBtn {
  display: flex;
  justify-content: space-between;
  width: 80%;
  margin: auto;
  padding-bottom: 1rem;
  background: #fff;
  margin-top: 0.5rem;
  .saveBtn {
    background: #ccc;
    color: #fff;
    width: 45%;
    margin: auto;
    text-align: center;
    padding: 0.25rem;
    border-radius: 5px;
    font-size: 0.3rem;
    margin-right: 0.2rem;
  }
  .submitBtn {
    background: #409eff;
    color: #fff;
    width: 45%;
    margin: auto;
    text-align: center;
    padding: 0.25rem;
    border-radius: 5px;
    font-size: 0.3rem;
  }
}
.car_title {
  padding: 0.2rem;
  font-size: 0.3rem;
  font-weight: bold;
  color: #333;
}
</style>
